﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;

namespace FDSimpleModelGenerator.Logging
{
    /// <summary>
    /// 使用日志
    /// </summary>
    public static class UseLoggingExtensions
    {
        /// <summary>
        /// 使用日志服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSysLogging(this IServiceCollection services)
        {
            var nlogPath = Path.Combine(AppContext.BaseDirectory, "nlog.config");
            if (!File.Exists(nlogPath))
            {
                using Stream streamCfg = Assembly.GetExecutingAssembly().GetManifestResourceStream($"{typeof(UseLoggingExtensions).Namespace}.nlog.config");
                using FileStream fs = new FileStream(nlogPath, FileMode.Create);
                var buffer = new byte[streamCfg.Length];
                Span<byte> sBuffer = new Span<byte>(buffer);
                var nLen = streamCfg.Read(sBuffer);
                fs.Write(sBuffer.ToArray(), 0, nLen);
            }
            services.AddLogging(config =>
            {
                config.AddNLog(new NLogProviderOptions
                {
                    CaptureMessageTemplates = true,
                    CaptureMessageProperties = true
                });
                NLog.LogManager.LoadConfiguration("nlog.config");
            });
            services.AddTransient(typeof(ILog<>), typeof(NLogger<>));
            services.AddTransient(typeof(ISystemLog<>), typeof(NLogger<>));
            
            return services;
        }
    }
}
